package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"time"
)

// 获取文章信息
func GetArticleInfo(p map[string]interface{}) *models.Article {
	o := orm.NewOrm()
	article := &models.Article{}
	qs := o.QueryTable("Article")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(article)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		article.CreatedShow = article.Created.Format("2006-01-02 15:04:05")
		article.UpdatedShow = article.Updated.Format("2006-01-02 15:04:05")
	}
	return article
}

// 添加文章信息
func AddArticle(input url.Values) (int64, error) {
	o := orm.NewOrm()
	article := &models.Article{}
	articleType := &models.ArticleType{}
	if _, ok := input["article_type_id"]; ok {
		articleType.Id = utils.Atoi64(input["article_type_id"][0])
		o.Read(articleType)
	}
	article.ArticleType = articleType
	if _, ok := input["title"]; ok {
		article.Title = input["title"][0]
	}
	if _, ok := input["content"]; ok {
		article.Content = input["content"][0]
	}
	if _, ok := input["sorted"]; ok {
		article.Sorted, _ = strconv.Atoi(input["sorted"][0])
	}
	return o.Insert(article)
}

// 修改文章信息
func EditArticle(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	p["updated"] = time.Now().Format("2006-01-02 15:04:05")
	return o.QueryTable("Article").Filter("id", input["id"][0]).Update(p)
}

// 获取文章列表
func GetArticleList(p map[string]interface{}) (int64, []*models.Article) {
	var articleList []*models.Article
	o := orm.NewOrm()
	qs := o.QueryTable("Article")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["articleTypeId"]; ok {
		qs = qs.Filter("article_type_id", p["articleTypeId"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-sorted").All(&articleList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, article := range articleList {
			article.CreatedShow = article.Created.Format("2006-01-02 15:04:05")
			article.UpdatedShow = article.Updated.Format("2006-01-02 15:04:05")
		}
	}
	return totalCount, articleList
}